<template>
  <base-container>
    <!-- 搜索栏 -->
    <avue-table-search
      :option="searchOption"
      v-model="searchParams"
      @search-change="loadTableSearch"
      @search-reset="loadTableSearchReset"
    />
    <!-- 卡片容器 -->
    <base-table-card>
      <template #header-left>
        <el-tabs v-model="searchParams.status" @tab-change="loadGetTableData">
          <el-tab-pane label="正常" :name="1" />
          <el-tab-pane label="已停用" :name="0" />
        </el-tabs>
      </template>
      <template #header-right>
        <el-button type="primary" v-auth="[PERMS.USER.ADD]" @click="handleGoToAddUser">新增成员</el-button>
      </template>
      <avue-crud
        ref="avueCrudRef"
        :option="tableOption"
        :data="tableData"
        v-model="formData"
        :page="page"
        :table-loading="tableLoading"
        @refresh-change="loadGetTableData"
        @current-change="loadTablePageChange"
        @size-change="loadTablePageSizeChange"
        @row-save="loadAdd"
        @row-update="loadEdit"
      >
        <template #roles="{ row }">
          <div class="nowrap cursor-pointer" v-if="row.roles && row.roles.length">
            <el-tag v-for="role in row.roles.slice(0, 2)" :key="role.id" class="mr8px" type="info" disable-transitions>
              {{ role.roleName }}
            </el-tag>
            <el-popover placement="top" :width="268" trigger="hover" v-if="row.roles.length > 2">
              <template #reference>
                <base-icon name="iconfont-general gen-gengduo" :size="20" color="var(--ct3)" />
              </template>
              <div class="flex-wrap">
                <el-tag class="m1" v-for="item in row.roles" :key="item.id" type="info" disable-transitions>
                  {{ item.roleName }}
                </el-tag>
              </div>
            </el-popover>
          </div>
        </template>
        <template #menu="{ row }">
          <el-button type="primary" text v-auth="[PERMS.USER.UPDATE]" @click="handleGotoUpdateUser(row.id)">
            编辑
          </el-button>
          <el-button
            type="primary"
            text
            v-auth="[PERMS.USER.ENABLE]"
            :disabled="row.statusLoading || row.isAdmin === 1"
            @click="handleStatusChange(row)"
          >
            {{ row.status === 1 ? "停用" : "启用" }}
          </el-button>
          <el-button type="info" text v-auth="[PERMS.USER.DELETE]" :disabled="row.status === 1" @click="loadDel(row)">
            删除
          </el-button>
        </template>
      </avue-crud>
    </base-table-card>
  </base-container>
</template>

<script setup>
  import Option from "@/crudOption/permission/user";

  // 获取全局方法
  const App = useGlobals();

  // 获取路由实例
  const router = useRouter();

  onMounted(() => {
    // 获取表格数据
    loadGetTableData();
  });

  // avue-crud 组件实例
  const avueCrudRef = ref({});

  // 增删改查 hook
  let {
    data: tableData,
    loading: tableLoading,
    page: page,
    search: searchParams,
    form: formData,
    get: loadGetTableData,
    add: loadAdd,
    edit: loadEdit,
    del: loadDel,
    pageNumChange: loadTablePageChange,
    pageSizeChange: loadTablePageSizeChange,
    searchReset: loadTableSearchReset,
    searchChange: loadTableSearch,
  } = useCrudHook({
    get: Api.user.GetUserPage,
    add: Api.user.AddUser,
    edit: Api.user.UpdateUser,
    del: Api.user.DeleteUser,
    search: { status: 1 },
    delConfirm: {
      title: "提示",
      content: "确认删除该成员吗？",
      type: "warning",
    },
    getParamsFormat: params => {
      // 新增时间
      if (params.createTime && params.createTime.length === 2) {
        params.createTimeStart = params.createTime[0];
        params.createTimeEnd = params.createTime[1];
      }
      // 编辑时间
      if (params.updateTime && params.updateTime.length === 2) {
        params.updateTimeStart = params.updateTime[0];
        params.updateTimeEnd = params.updateTime[1];
      }
      // 删除多余参数
      delete params.createTime;
      delete params.updateTime;
      // 返回查询参数
      return params;
    },
  });

  // 获取 搜索配置 和 表格配置
  const { searchOption, tableOption } = Option(formData);

  // 跳转到新增页面
  const handleGoToAddUser = () => {
    router.push({ path: ROUTE_PATHS.USER.ADD });
  };

  // 跳转到编辑页面
  const handleGotoUpdateUser = userId => {
    router.push({ path: ROUTE_PATHS.USER.UPDATE, query: { userId } });
  };

  // 成员状态启用/禁用切换
  const handleStatusChange = row => {
    App.$confirm(`是否${row.status === 1 ? "停用" : "启用"}该成员？`, "提示", {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      type: "warning",
    }).then(() => {
      const status = row.status === 1 ? 0 : 1; // 先取反
      row.statusLoading = true;
      Api.user
        .ChangeUserStatus({ id: row.id, status: status })
        .then(() => {
          // 操作结果
          $msg.success(status ? "启用成功" : "停用成功");
          // 重新加载表格数据
          loadGetTableData();
        })
        .finally(() => {
          row.statusLoading = false;
        });
    });
  };

  // 监听权限变化，更新操作栏是否显示
  tableOption.value.menu = computed(() => hasAuth([PERMS.USER.UPDATE, PERMS.USER.ENABLE, PERMS.USER.DELETE]));

  // 监听菜单操作权限变化，更新操作菜单宽度
  tableOption.value.menuWidth = computed(() => {
    let width = 0;
    if (hasAuth(PERMS.USER.UPDATE)) width += 60;
    if (hasAuth(PERMS.USER.ENABLE)) width += 60;
    if (hasAuth(PERMS.USER.DELETE)) width += 60;
    return width;
  });
</script>
<style lang="scss" scoped></style>
